# encoding:utf-8
import os
import sys
import requests
from jenkins import Jenkins
from openpyxl import Workbook
from openpyxl.styles import Alignment
from openpyxl.utils import get_column_letter
from utils.others_tool.other_tool import get_opt
from utils.time_tool.time_control import Getdate
from config.all_paths import get_root_path,config_variable_path
from utils.file_handling.txt_handling import read_big_txt

jenkins_url = "http://106.75.225.58:8080/"
server = Jenkins(jenkins_url, username='admin', password='9d0c48a873cc473db6edad78b819a4fa')
job_name = "job/HIS-ALL"
job_url = server.get_info(job_name)['url']
job_last_number = server.get_info(job_name)['lastBuild']['number']
report_url = job_url + str(job_last_number) + '/allure'
excel_result_url = job_url+"ws/data/"

# 测试发布环境的地址
webhook_test = 'https://oapi.dingtalk.com/robot/send?access_token=95e872da7b500a7c1a692559f6aafdbeda1ba6e0ecf5457a19151d06fa3a184f'
# 玄武
webhook_his = r'https://oapi.dingtalk.com/robot/send?access_token=9668ee98fc0428f016891b9aaac92eb8466a002d87a2289bc124700a01442ad1'
# 技术部内部推送
webhook_it = r'https://oapi.dingtalk.com/robot/send?access_token=3121a21d799dadaa66c03026f6e8efee86c533bbc46d304382ce6b36f4489881'



def write_txt(text_file, data):
    """追加写入txt文件"""
    with open(text_file, 'a', encoding='gbk') as f:
        f.write(data)
        f.write('\n')  # 换行


def writeToEXCEL(data):
    # 创建一个新的Workbook对象
    wb = Workbook()

    # 选择活动工作表
    ws = wb.active

    # 写入表头
    headers = ['诊所名称','结论','vix条数/接种金额','vsms条数/接种金额','异常信息']
    for col_num, header in enumerate(headers, 1):
        ws.cell(row=1, column=col_num, value=header)

    # 写入数据
    for row_num, row_data in enumerate(data, 2):
        for col_num, value in enumerate(row_data.values(), 1):
            ws.cell(row=row_num, column=col_num, value=value)

    # 保存Excel文件
    wb.save(os.path.join(get_root_path(),'data',"output_1.xlsx"))

def writeToEXCEL_1(data):
    # 创建一个新的Workbook对象
    wb = Workbook()

    # 选择活动工作表
    ws = wb.active

    # 设置列宽
    column_widths = [30, 30, 20, 20, 70]  # 设置每列的宽度
    for col_num, width in enumerate(column_widths, 1):
        column_letter = get_column_letter(col_num)
        ws.column_dimensions[column_letter].width = width

    # 写入表头
    headers = ['诊所名称', '结论', 'vix条数/接种金额', 'vsms条数/接种金额', '异常信息']
    for col_num, header in enumerate(headers, 1):
        ws.cell(row=1, column=col_num, value=header)

    # 冻结表头
    ws.freeze_panes = "A2"


    # 写入数据
    for row_num, row_data in enumerate(data, 2):
        for col_num, value in enumerate(row_data.values(), 1):
            if col_num != len(headers):
                cell = ws.cell(row=row_num, column=col_num, value=value)
            if col_num == len(headers):  # 处理异常信息列
                # 设置单元格对齐方式为换行
                cell = ws.cell(row=row_num, column=col_num)

                # 写入每个异常信息列表元素的新行
                exception_info = value  # 假设异常信息已经是一个列表
                cell.value = '\n'.join(exception_info)
            cell.alignment = Alignment(horizontal='left', vertical='center', wrapText=True)

    # 保存Excel文件
    wb.save(os.path.join(get_root_path(), 'data', "output_1.xlsx"))

# 处理数据
def dealData(hisvalue):
    error_data = []
    # 源列表
    vix_details = hisvalue['vix']['详细记录']
    vsms_details = hisvalue['vsms']['详细记录']

    if len(vix_details) > len(vsms_details):
        error_data.append(f'两边系统的数据条数不一致,vsms的条数是{len(vsms_details)},vix的条数是{len(vix_details)}')
        for vix_detail in vix_details:
            deal_vix_jzsr = vix_detail['vaccinationIncome']
            if deal_vix_jzsr == '' or deal_vix_jzsr is None:
                deal_vix_jzsr = 0
            vix_jzsr = float(deal_vix_jzsr)
            phone = vix_detail['phone'].strip()
            customerName = vix_detail['customerName']
            for vsms_detail in vsms_details:
                if vsms_detail['phoneNumber'] == phone and vsms_detail['name'] == customerName:
                    deal_vsms_jzsr = vsms_detail['jzTotalIncome']
                    if deal_vsms_jzsr == '' or deal_vsms_jzsr is None:
                        deal_vsms_jzsr = 0
                    vsms_jzsr = float(deal_vsms_jzsr)
                    if int(vix_jzsr) == int(vsms_jzsr):
                        print(customerName + "-" + phone + ":校验通过")
                    else:
                        print(customerName + "-" + phone + ":校验异常")
                        error_data.append(customerName + "-" + phone + "  |vsms接种收入：" + str(
                            vsms_jzsr) + "  |vix接种收入：" + str(vix_jzsr))
                    break
                if vsms_detail == vsms_details[-1]:
                    if vsms_detail['phoneNumber'] != phone and vsms_detail['name'] != customerName:
                        print(customerName + "-" + phone + ":两边用户不匹配")
                        error_data.append(customerName + "-" + phone + ":两边用户不匹配")


    if len(vsms_details) > len(vix_details):
        error_data.append(f'两边系统的数据条数不一致,vsms的条数是{len(vsms_details)},vix的条数是{len(vix_details)}')
        for vsms_detail in vsms_details:
            deal_vsms_jzsr = vsms_detail['jzTotalIncome']
            if deal_vsms_jzsr == '' or deal_vsms_jzsr is None:
                deal_vsms_jzsr = 0
            vsms_jzsr = float(deal_vsms_jzsr)
            phone = vsms_detail['phoneNumber'].strip()
            customerName = vsms_detail['name']
            for vix_detail in vix_details:
                if vix_detail['phone'] == phone and vix_detail['customerName'] == customerName:
                    deal_vix_jzsr = vix_detail['vaccinationIncome']
                    if deal_vix_jzsr == '' or deal_vix_jzsr is None:
                        deal_vix_jzsr = 0
                    vix_jzsr = float(deal_vix_jzsr)
                    if int(vix_jzsr) == int(vsms_jzsr):
                        print(customerName + "-" + phone + ":校验通过")
                    else:
                        print(customerName + "-" + phone + ":校验异常")
                        error_data.append(customerName + "-" + phone + "  |vsms接种收入：" + str(
                            vsms_jzsr) + "  |vix接种收入：" + str(vix_jzsr))
                    break
                if vix_detail == vix_details[-1]:
                    if vix_detail['phone'] != phone and vix_detail['customerName'] != customerName:
                        print(customerName + "-" + phone + ":两边用户不匹配")
                        error_data.append(customerName + "-" + phone + ":两边用户不匹配")

    if len(vix_details) == len(vsms_details):
        for vsms_detail in vsms_details:
            deal_vsms_jzsr = vsms_detail['jzTotalIncome']
            if deal_vsms_jzsr == '' or deal_vsms_jzsr is None:
                deal_vsms_jzsr = 0
            vsms_jzsr = float(deal_vsms_jzsr)
            phone = vsms_detail['phoneNumber'].strip()
            customerName = vsms_detail['name']
            for vix_detail in vix_details:
                if vix_detail['phone'] == phone and vix_detail['customerName'] == customerName:
                    deal_vix_jzsr = vix_detail['vaccinationIncome']
                    if deal_vix_jzsr == '' or deal_vix_jzsr is None:
                        deal_vix_jzsr = 0
                    vix_jzsr = float(deal_vix_jzsr)
                    if int(vix_jzsr) == int(vsms_jzsr):
                        print(customerName + "-" + phone + ":校验通过")
                    else:
                        print(customerName + "-" + phone + ":校验异常")
                        error_data.append(customerName + "-" + phone + "  |vsms接种收入：" + str(
                            vsms_jzsr) + "  |vix接种收入：" + str(vix_jzsr))
                    break
                if vix_detail == vix_details[-1]:
                    if vix_detail['phone'] != phone and vix_detail['customerName'] != customerName:
                        print(customerName + "-" + phone + ":两边用户不匹配")
                        error_data.append(customerName + "-" + phone + ":两边用户不匹配")

    return error_data



def push_message_vix(all_num, normal_num,error_num,faild_num, webhook=webhook_it):
    excel_result_url1 = excel_result_url + "output_1.xlsx"
    print(excel_result_url1)
    content = {
        "msgtype": "markdown",
        "markdown": {
            "title": "自动化监测结果",
            "text": f'### {Getdate().getYesterday()}' + ' ' + f'{Getdate().getWeekdayYesterday()}'
                    + "\n#### 共校验his门诊数量："+ f"{all_num}"
                    + "\n#### 正常门诊数量：" + f"{normal_num}"
                    + "\n#### 异常门诊数量：" + f"{error_num}"
                    + "\n#### 无数据门诊数量: " + f"{faild_num}"
                    + "\n#### 异常信息详情: " + f"[Excel]({excel_result_url1})"
        }}
    requests.post(url=webhook, json=content, verify=False)



if __name__ == '__main__':
    t_opt = get_opt(sys.argv[1:])
    type = t_opt.get('type')
    A = eval(read_big_txt(config_variable_path))

    data_list = []
    normal_num = 0
    error_num = 0
    faild_num = 0
    all_num = 0

    for key,value in A.items():
        all_num = all_num + 1
        flag = True
        name = key  # 诊所名称
        value_dict = value
        result = '' # 结论
        vix_message = ''
        vsms_message = ''
        error_data = ''
        if value_dict['vix']['总条数'] == 0 or value_dict['vsms']['总条数'] == 0:
            if value_dict['vix']['总条数'] == 0:
                result = 'vix没有数据，无法比较'
            if value_dict['vsms']['总条数'] == 0:
                result = 'vsms没有数据，无法比较'
            faild_num = faild_num + 1
        else:
            vix_message = f"{value_dict['vix']['总条数']}/{value_dict['vix']['接种收入']}"
            vsms_message = f"{value_dict['vsms']['总条数']}/{value_dict['vsms']['接种收入']}"
            try:
                error_data = dealData(value_dict)
            except Exception as e:
                print(name, '数据异常')
                print('错误类型是', e.__class__.__name__)
                print('错误明细是：', e)
            if error_data == []:
                result = '正常'
                normal_num = normal_num + 1
            else:
                result = '异常'
                error_num = error_num + 1

        tem_dict = {}
        tem_dict['name'] = name
        tem_dict['result'] = result
        tem_dict['vix_message'] = vix_message
        tem_dict['vsms_message'] = vsms_message
        # tem_dict['error_data'] = str(error_data)
        tem_dict['error_data'] = error_data
        data_list.append(tem_dict)

    # print(data_list)
    #
    writeToEXCEL_1(data_list)
    if type == 'pro':
        push_message_vix(all_num, normal_num,error_num,faild_num, webhook=webhook_his)
    if type == 'test':
        push_message_vix(all_num, normal_num,error_num,faild_num, webhook=webhook_test)


    # python main.py --env=pro_vix --mark=vix_pro
    # python send_dingding_vix_shoufeiribao_003.py --type=test
